<?php

namespace app\commons;

use yii\base\Exception as BaseException;
use yii\base\UserException as Exception;
use yii\base\Model;

/**
 *
 * 非系统原因报错，支持返回数组和字符串错误信息
 */
class ApiException extends Exception
{
    public String $model;

    private array $errMessage = [
        500 => 'unknown error', // 默认错误码
        402 => 'non-sign',
        403 => 'sing timeout',
        404 => 'server non-exist',
        405 => 'sign error',
        406 => 'params error',
        501 => 'server busy now',//用于限流的时候，用于数据库异常
    ];

    public function __construct($code, $message = '', \Exception $previous = null)
    {
        //parent::__construct($message, $code, $previous);
        if (is_array($message)) {
            $this->arrMessage = $message;
            $error = array_shift($message);
            $this->message = is_array($error) ? $error[0] : $error;
        } else if (is_string($message)) {
            $this->message = $message;
        } else if ($message instanceof Model) {
            $this->model = $message;
        } else {
            throw new BaseException ($this->errMessage[500],500);
        }

        if (empty($this->message) && isset($this->errMessage[$code]) ) {
            $this->message = $this->errMessage[$code];
        }

        $this->code = $code;
    }

    public function getName(): string
    {
        return 'ApiException';
    }

}
